<?php

class Mysql implements DBInterface {

    private $link;

    public function fetchArray($result) {
        return mysql_fetch_assoc($result);
    }

    public function getConection($dsn) {
        $param = array();
        $param['host'] = isset($dsn['host']) ? $dsn['host'] : 'localhost';
        $param['dbname'] = substr($dsn['path'], 1);
        foreach (explode('&', $dsn['query']) as $q) {
            list($k, $v) = explode('=', $q);
            $param[$k] = $v;
        }
        $param['username'] = isset($param['username']) ? $param['username'] : 'root';
        $param['password'] = isset($param['password']) ? $param['password'] : '';
        $param['charset'] = isset($param['charset']) ? $param['charset'] : '';
        $param['pconnect'] = isset($param['pconnect']) ? (bool) $param['pconnect'] : 0;

        $func = ($param['pconnect'] ? 'mysql_pconnect' : 'mysql_connect');

        $this->link = @$func($param['host'], $param['username'], $param['password'], 1);
        if (!$this->link)
            throw new DBExcepton("Can't conect to {$param['host']} use {$param['username']}");

        if ($param['dbname']) {
            mysql_select_db($param['dbname'], $this->link);
        }

        if ($param['charset']) {
            $this->query("SET NAMES '{$param['charset']}'");
        }
    }

    public function query($sql) {
        $result = @mysql_query($sql, $this->link);
        if (!$result)
            throw new DBExcepton(mysql_error($this->link) . "<br/>$sql");
        if (preg_match("/^INSERT/i", $sql)) {
            $result = mysql_insert_id($this->link);
            if (!$result)
                $result = true;
        }
        return $result;
    }

    public function version() {
        return mysql_get_server_info($this->link);
    }

}

?>
